package com.marktotop.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.marktotop.entity.business.VaccinationRecord;
import com.marktotop.entity.business.VaccineHistory;
import com.marktotop.error.SystemCodeEnum;
import com.marktotop.error.SystemException;
import com.marktotop.mapper.VaccinationRecordMapper;
import com.marktotop.service.IReservationRecordService;
import com.marktotop.service.IVaccinationRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.marktotop.service.IVaccineHistoryService;
import com.marktotop.vo.business.InoculateVO;
import com.marktotop.vo.business.ReservationRecordVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author MarkToTop
 * @since 2021-07-12
 */
@Service
public class VaccinationRecordServiceImpl extends ServiceImpl<VaccinationRecordMapper, VaccinationRecord> implements IVaccinationRecordService {

    @Autowired
    private IReservationRecordService recordService;

    @Autowired
    private VaccinationRecordMapper vaccinationRecordMapper;

    @Autowired
    private IVaccineHistoryService historyService;

    /**
     * 提交接种记录
     *
     * @param vaccinationRecord 接种单
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean postInoculateVaccine(VaccinationRecord vaccinationRecord) throws SystemException {
        // 根据 预约号 和 预约状态 查到对应的预约信息
        ReservationRecordVO record = recordService.getOneRecord(vaccinationRecord.getReservationId());
        if (null == record ){
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"未找到相关预约信息,请核实后重试！");
        }
        // 如果接种疫苗 和 预约的疫苗不一致，不能接种
        if (!record.getVaccineId().equals(vaccinationRecord.getVaccNumber())){
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"所接种的疫苗与预约信息不符,请核实后重试！");
        }
        // 判断预约的第几针和注射的针，是否相符
        if (!record.getVaccineNeedle().equals(vaccinationRecord.getVaccAmount())){
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"注射信息与该预约信息不相符,请查证后重试！");
        }
        // 判断当前接种人是否有对应疫苗接种历史
        Long vaccinatorId = vaccinationRecord.getVaccinatorId();
        Long vaccNumber = vaccinationRecord.getVaccNumber();
        if (historyService.haveVaccineRecord(vaccinatorId,vaccNumber)){
            //有疫苗记录 - 判断当前接种注射针数 是否大于等于已注射针数
            if (historyService.getVaccineRecord(vaccinatorId,vaccNumber,vaccinationRecord.getVaccAmount())){
                //已经接种过该疫苗的第本次针
                return false;
            }
            //判断本次接种针数是否和记录中相匹配 (接种数 = 记录数 + 1)
            VaccineHistory historyRecord = historyService.getVaccineRecord(vaccinatorId, vaccNumber);
            int injectionCount =  historyRecord.getInjectionCount() + 1;
            if (!vaccinationRecord.getVaccAmount().equals(injectionCount)){
                throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"注射信息与您的疫苗历史信息不相符,请查证后重试！");
            }
            // 相匹配，先更新疫苗历史记录
            if (!historyService.update(new UpdateWrapper<VaccineHistory>().eq("vaccinator_id",vaccinatorId).eq("vaccine_id",vaccNumber).set("injection_count",vaccinationRecord.getVaccAmount()))){
                return false;
            }
        } else {
            //如果疫苗历史为空，先创建疫苗历史
            VaccineHistory history = new VaccineHistory()
                    .setVaccinatorId(vaccinatorId)
                    .setVaccineId(vaccNumber)
                    .setLastVaccSite(vaccinationRecord.getVaccSiteName())
                    .setVaccineName(record.getVaccineName())
                    .setTotalCount(record.getTotalNeedle())
                    // 首次注射，已注射数为1
                    .setInjectionCount(1)
                    .setVaccConsumer(record.getSupplierName())
                    .setFirstInjectTime(new Date())
                    .setUpdateTime(new Date());
            if (!historyService.save(history)){
                throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"接种疫苗历史信息建立失败,请重新登记！");
            }
        }
        // 最后根据预约信息 - 存入接种记录
        vaccinationRecord.setAccountTime(new Date());
        if (vaccinationRecordMapper.insert(vaccinationRecord) == 0) {
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR, "接种信息建立失败,请重新登记！");
        }
        // 修改预约状态
        Integer states = record.getStates();
        if (!recordService.updateRecordStates(record.getId(), states + 1)){
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"更新预约状态失败,请手动更新预约状态！");
        }
        return true;
    }


    /**
     * 获取单个受理的接种信息
     *
     * @param id
     * @return
     * @throws SystemException
     */
    @Override
    public InoculateVO getOneInoculateRecord(Long id) throws SystemException {
        InoculateVO oneInoculateRecord =  vaccinationRecordMapper.selectOneInoculateRecord(id);
        if (null == oneInoculateRecord){
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"没有找到相应的预约接种申请信息！");
        }
//        if (oneInoculateRecord.getStates() != 1){
//            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"该预约申请信息状态不是已受理状态，请核实！");
//        }
        return oneInoculateRecord;
    }
}
